package data

import (
	"github.com/Shopify/sarama"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/wire"

	"VideoMemberCard/app/payment/task/internal/conf"
	"VideoMemberCard/app/payment/task/internal/data/ent"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewPaymentRepo, NewEntClient, NewRedis, NewKafkaConsumenr)

// Data .
type Data struct {
	db    *ent.Client
	redis *redis.Client
	kc    sarama.Consumer
	log   *log.Helper
}

// NewData .
func NewData(db *ent.Client, redis *redis.Client, kc sarama.Consumer, logger log.Logger) (*Data, func(), error) {
	log := log.NewHelper(log.With(logger, "module", "payment-task/data"))

	d := &Data{
		db:    db,
		redis: redis,
		kc:    kc,
		log:   log,
	}
	return d, func() {
		if err := d.db.Close(); err != nil {
			log.Error(err)
		}
	}, nil
}

func NewEntClient(conf *conf.Data, logger log.Logger) *ent.Client {
	log := log.NewHelper(log.With(logger, "module", "payment-task/data/ent"))

	client, err := ent.Open(
		conf.Database.Driver,
		conf.Database.Source,
	)
	if err != nil {
		log.Fatalf("failed opening connection to db: %v", err)
	}
	return client
}

func NewRedis(conf *conf.Data) *redis.Client {
	var options redis.Options
	options.Addr = conf.Redis.Addr
	client := redis.NewClient(&options)
	return client
}

func NewKafkaConsumenr(conf *conf.Data) sarama.Consumer {
	c := sarama.NewConfig()
	p, err := sarama.NewConsumer(conf.Kafka.Addrs, c)
	if err != nil {
		panic(err)
	}
	return p
}
